﻿using FreeRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.Caching;

namespace Shared.Caching.FreeRedis;
/// <summary>
/// FreeRedis缓存模块
/// </summary>
[DependsOn(typeof(AbpCachingModule))]
public class FreeRedisCacheModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();
            
        var redisEnabled = configuration["Redis:IsEnabled"];
        
        if (redisEnabled.IsNullOrEmpty() || bool.Parse(redisEnabled))
        {
            var redisConfiguration = configuration["Redis:Configuration"];
            
            RedisClient redisClient = new RedisClient(redisConfiguration);

            // 注册 RedisClient
            context.Services.AddSingleton<RedisClient>(redisClient);
                
            // 替换 IDistributedCache 实现
            context.Services.Replace(ServiceDescriptor.Singleton<IDistributedCache>(
                new DistributedCache(redisClient)
            ));
        }

        // 配置ABP框架的缓存选项
        Configure<AbpDistributedCacheOptions>(options =>
        {
            // 配置全局缓存键前缀
            options.KeyPrefix = configuration["Redis:KeyPrefix"] ?? "app:";
                
            // 配置全局缓存过期时间默认值
            options.GlobalCacheEntryOptions.AbsoluteExpirationRelativeToNow = 
                System.TimeSpan.FromHours(1);
        });
    }
}